<template>
  <!-- 顶部 -->
  <div class="category_header">
    <CategoryHeader></CategoryHeader>
  </div>
  <div class="category_container">
    <!-- 左侧 -->
    <el-scrollbar height="92vh" noresize @scroll="scrollHandler" :scrollTo="scrollNum">
      <a v-for="(item, index) in categoryList" :href="'#' + index">
        <Menu class="left_nav" :class="{ active: index == activeIndex }" :key="item.id" :item="item" :index="index"
          @getItemIndex="getItemIndex" @click="scrollToPosition(index)">
        </Menu>
      </a>
    </el-scrollbar>

    <!-- 右侧 -->
    <div class="right_container">
      <el-scrollbar height="92vh" noresize @scroll="activeNavNode">
        <Category v-for="(item, index) in categoryList" :key="item.id" :item="item" :index="index"
          :activeIndex="activeIndex" :id="index" class="right_scroll"></Category>
      </el-scrollbar>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Menu from "@/views/classification/components/Menu/index.vue"
import Category from "@/views/classification/components/Category/index.vue"
import CategoryHeader from "@/components/CategoryHeader.vue";
import { ref, onMounted } from "vue"

import type { AnyObject } from "@/types/category";
import { reqCategoryList } from "@/apis/category"


/* 定义响应式数据 */
let categoryList = ref<AnyObject[]>([])
let activeIndex = ref(0)
let scrollNum = ref("")


/* 生命周期 */
onMounted(() => {
  getCategoryList()
})

/* 获取分类列表的功能函数 */
const getCategoryList = async () => {
  try {
    let res = await reqCategoryList()
    if (res.ret == 0) {
      categoryList.value = res.data
    }
  } catch (error) {
    console.log(error);

  }
}

/* 滚动的回调 */
const scrollHandler = (res: any) => {
}

/* 左侧导航自定义事件 */
const getItemIndex = (index: number) => {
  if (activeIndex.value == index) {
    return
  } {

    activeIndex.value = index
  }
}

/* 点击左侧的回调 */
const scrollToPosition = (index: number) => {
  document.getElementsByClassName("left_nav")[index].scrollIntoView()
}

/* 右侧的滚动回调 */
const activeNavNode = () => {
  const nodes = document.getElementsByClassName("right_scroll")
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i]
    let nodeY = node.getBoundingClientRect().top
    if (nodeY <= 100 && nodeY >= 0) {
      activeIndex.value = i
      document.getElementsByClassName("left_nav")[activeIndex.value].scrollIntoView()
    }
  }
}
</script>
<style lang="less" scoped>
.category_container {
  display: flex;
}

.active {
  border-left: 6px solid #f86442;
}
</style>